package com.diandi.signature.manager.impl.contract;


import com.diandi.signature.bean.contract.SignatureContract;
import com.diandi.signature.bean.contract.SignatureContractDetail;
import com.diandi.signature.bean.pkgmsg.SignatureBusinessPkgmsg;
import com.diandi.signature.bean.pkgmsg.SignaturePlatformPkgMsg;
import com.diandi.signature.bean.proceessinfo.SignatureProcessDetail;
import com.diandi.signature.bean.proceessinfo.SignatureProcessLog;
import com.diandi.signature.enums.fdd.ContractStatus;
import com.diandi.signature.enums.platfrom.*;
import com.diandi.signature.manager.contract.SignatureContractManager;
import com.diandi.signature.mapper.*;
import com.diandi.signature.properties.SignatureProperties;
import com.diandi.signature.sign.SignUtil;
import com.diandi.signature.sign.Tools;
import com.diandi.signature.utils.CallServiceUtil;
import com.diandi.signature.utils.PackageParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @author mwz
* @create 2017-08-23 13:47
* @version V1.0.0
* @description description
*/
@Component
public class SignatureContractManagerImpl implements SignatureContractManager {


    /**
     * CA认证
     */
    @Autowired
    private SignatureCAInfoMapper signatureCAInfoMapper;

    /**
     * 签章处理过程主表
     */
    @Autowired
    private SignatureProcessLogMapper signatureProcessLogMapper;

    /**
     * 签章处理过程子表
     */
    @Autowired
    private SignatureProcessDetailMapper signatureProcessDetailMapper;

    @Autowired
    private SignaturePlatformPkgmsgMapper signaturePlatformPkgmsgMapper;
    @Autowired
    private SignatureBusinessPkgmsgMapper signatureBusinessPkgmsgMapper;

    @Autowired
    private SignatureContractMapper signatureContractInfoMapper;
    @Autowired
    private SignatureContractDetailMapper signatureContractDetailMapper  ;

    @Autowired
    private SignatureProperties signatureProperties;

    @Override
    public SignatureContract getSignatureContractByCode(Map<String, Object> paramMap) {
        return signatureContractInfoMapper.getSignatureContractByCode( paramMap );
    }

    @Transactional
    @Override
    public SignatureContract insertSignatureContractInfo(Map<String, String> params) throws Exception {

        SignatureContract contract = new SignatureContract();
        contract.setSignatureCode( params.get("platTradeNo") );
        contract.setContractBatchCode( params.get("contractNo") );
        contract.setContractCode( params.get("contractNo") );
        contract.setUserId( Long.valueOf(params.get("userId")) );
        contract.setContractTemplateCode( params.get("templateCode") );
        contract.setBorrowId( Long.valueOf(params.get("borrowId") ) );
        contract.setPassCode(  params.get("passCode") );
        contract.setMerchantNo( params.get("merchantNo"));
        contract.setContractTitle( params.get("contractTitle"));
        contract.setStatus( Integer.parseInt( ContractStatus.合同信息落库.getType() ) );
        signatureContractInfoMapper.insertSignatureContract( contract );
        return contract;
    }

    @Transactional
    @Override
    public SignatureContract signatureSaveData(  Map<String, String> params) throws Exception {

        /**1.1、插入合同主表数据*/
        SignatureContract signatureContractInfo = PackageParams.getSignatureContractPkgmsg( params );
        signatureContractInfoMapper.insertSignatureContract( signatureContractInfo );

        /**1.2、插入合同明细*/

        SignatureContractDetail signatureContractDetail =  PackageParams.getSignatureContractDetailPkgMsg( params );
        signatureContractDetailMapper.insertSignatureContractDetail( signatureContractDetail );

        /**2.1、插入状态主表数据*/
        SignatureProcessLog  signatureProcessLog =  PackageParams.getInitSignatureProcessLogtPkgMsg( params );
        signatureProcessLogMapper.insertSignatureProcessLog(signatureProcessLog);
        params.put("signatureProcessLogId",signatureProcessLog.getId().toString());
        /**2.2、插入状态明细数据*/
        SignatureProcessDetail signatureProcessDetail =  PackageParams.getSignatureProcessDetailPkgMsg( params );
        signatureProcessDetailMapper.insertSignatureProcessDetail(signatureProcessDetail);


        /**2.2、插入报文信息*/
        Map<String, String> paramMap = new HashMap<String, String>();
        paramMap.putAll(params);

        paramMap.put("requestMsg",params.toString());
        paramMap.put("returnMsg","");
        paramMap.put("unnotifyMsg","");
        SignatureBusinessPkgmsg signatureBusinessPkgmsg = PackageParams.getBusinessPkgmsg( paramMap );
        signatureBusinessPkgmsgMapper.insertSignatureBusinessPkgmsg( signatureBusinessPkgmsg );
        return signatureContractInfo;
    }


    @Transactional
    @Override
    public SignatureContract saveSignatureProcess(  Map<String, String> params) throws Exception {

        /**1.1、插入合同主表数据*/
        SignatureContract signatureContractInfo = PackageParams.getSignatureContractPkgmsg( params );
        signatureContractInfoMapper.insertSignatureContract( signatureContractInfo );

        /**2.1、插入状态主表数据*/
        SignatureProcessLog  signatureProcessLog =  PackageParams.getInitSignatureProcessLogtPkgMsg( params );
        signatureProcessLogMapper.insertSignatureProcessLog(signatureProcessLog);
        params.put("signatureProcessLogId",signatureProcessLog.getId().toString());
        /**2.2、插入状态明细数据*/
       /* SignatureProcessDetail signatureProcessDetail =  PackageParams.getSignatureProcessDetailPkgMsg( params );
        signatureProcessDetailMapper.insertSignatureProcessDetail(signatureProcessDetail);*/


        /**2.2、插入报文信息*/
        /*
        Map<String, String> paramMap = new HashMap<String, String>();
        paramMap.putAll(params);

        paramMap.put("requestMsg",params.toString());
        paramMap.put("returnMsg","");
        paramMap.put("unnotifyMsg","");
        SignatureBusinessPkgmsg signatureBusinessPkgmsg = PackageParams.getBusinessPkgmsg( paramMap );
        signatureBusinessPkgmsgMapper.insertSignatureBusinessPkgmsg( signatureBusinessPkgmsg );*/

        return signatureContractInfo;
    }

    @Override
    public Integer updateIsArchives(String contractCode, String isArchives) {
        Map<String, String> updateContInfo = new HashMap<String, String>();
        updateContInfo.put("contractNo", contractCode);
        updateContInfo.put("isArchives", "1");
        return signatureContractInfoMapper.updateUrlsByConNo(updateContInfo);
    }

    @Override
    public List<SignatureContract> queryTask(Map<String, Object> paramMap) {
        return signatureContractInfoMapper.queryTask(paramMap);
    }

    /**
     * 异步通知业务端
     * @param code 状态码
     * @param msg 响应信息
     * @param contractNo 合同编号
     * @param nUrl 业务端地址
     * @return
     */
    @Override
    public String callBusiness(String code, String msg, String contractNo, String nUrl, String merchantNo) {
        Map<String, Object> queryMap = new HashMap<String, Object>();
        queryMap.put("contractNo", contractNo);
        //查询合同表，查询url
        SignatureContract contract = signatureContractInfoMapper.getContract(queryMap);
        if (contract == null){
            return "error";
        }

        Map<String, String> pkgMsgMap = new HashMap<String, String >();
        pkgMsgMap.put("responseCode",code);
        pkgMsgMap.put("responseMsg",msg);
        pkgMsgMap.put("contractNo", contractNo);
        pkgMsgMap.put("downloadUrl",contract.getContractDownloadUrl());
        pkgMsgMap.put("viewpdfUrl",contract.getContractViewUrl());
        try {
            String sign = SignUtil.signRSA(pkgMsgMap, signatureProperties.getPayPrivateSign(merchantNo), signatureProperties.getCharset());
            pkgMsgMap.put("sign", sign);
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }
        String pgkMsg = Tools.createBusinessLinkString( pkgMsgMap,true,"utf-8");
        return CallServiceUtil.sendPost(nUrl, pgkMsg);
    }

    @Override
    public String callBusiness(String code, String msg, String contractNo, String dUrl, String vUrl, String nUrl, String merchantNo) {
        Map<String, String> pkgMsgMap = new HashMap<String, String >();
        pkgMsgMap.put("responseCode",code);
        pkgMsgMap.put("responseMsg",msg);
        pkgMsgMap.put("contractNo", contractNo);
        pkgMsgMap.put("downloadUrl",dUrl);
        pkgMsgMap.put("viewpdfUrl",vUrl);
        try {
            String sign = SignUtil.signRSA(pkgMsgMap, signatureProperties.getPayPrivateSign(merchantNo), signatureProperties.getCharset());
            pkgMsgMap.put("sign", sign);
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }
        String pgkMsg = Tools.createBusinessLinkString( pkgMsgMap,true,"utf-8");
        return CallServiceUtil.sendPost(nUrl, pgkMsg);
    }

    /**
     * 插入过程信息
     * 发送到通道消息
     * @param params
     * @return
     * @throws Exception
     */
    @Transactional
    @Override
    public boolean insertProcessInfoData(SignatureContract signatureContract,Map<String, String> params,Integer processFlag) throws Exception {


        /**2.1、插入状态主表数据*/
        SignatureProcessLog  signatureProcessLog =  PackageParams.getInitSignatureProcessLogtPkgMsg( params );
        signatureProcessLog.setInterfaceType( processFlag );
        signatureProcessLogMapper.updateSignatureProcessLog( signatureProcessLog );

        /**2.2、插入状态明细数据*/
        SignatureProcessDetail signatureProcessDetail =  PackageParams.getSignatureProcessDetailPkgMsg( params );
        signatureProcessDetailMapper.insertSignatureProcessDetail(signatureProcessDetail);

        /**2.2、插入报文信息*/
        Map<String, String> paramMap = new HashMap<String, String>();
        paramMap.putAll(params);

        paramMap.put("requestMsg",params.toString());
        paramMap.put("returnMsg","");
        paramMap.put("unnotifyMsg","");
        SignaturePlatformPkgMsg signaturePlatformPkgMsg = PackageParams.getPlatFormPkgmsg( paramMap );
        signaturePlatformPkgmsgMapper.insertSignaturePlatformPkgmsg( signaturePlatformPkgMsg );
        return false;
    }

    @Transactional
    @Override
    public SignatureContract updateProcessInfoData(SignatureContract signatureContract,Map<String, String> params,Integer processFlag ) throws Exception {

        /**2.1、更新状态主表数据*/
        SignatureContract contract = new SignatureContract();
        Map<String, String> queryParams = new HashMap<String,String>();
        queryParams.put("signatureCode",signatureContract.getSignatureCode() );
        queryParams.put("contractCode",signatureContract.getContractCode() );
        queryParams.put("userId",   String.valueOf( signatureContract.getUserId() ) );
        SignatureProcessLog  signatureProcessLog = signatureProcessLogMapper.getSignatureProcessLogByCode(queryParams);
        signatureProcessLog.setInterfaceType( processFlag );
        signatureProcessLog.setBusinessStatus(BusinessStatus.处理中.getStatus());
        signatureProcessLog.setPlatformStatus(PlatFormStatus.处理中.getStatus());
        signatureProcessLog.setPassStatus( PassStatus.待受理.getStatus());
        signatureProcessLog.setProcessFlag(ProcessFlag.处理中.getType() );
        signatureProcessLogMapper.updateSignatureProcessLog( signatureProcessLog );

        /**2.2、插入状态明细数据*/
        SignatureProcessDetail signatureProcessDetail =  PackageParams.getUpdateProcessDetailPkgMsg( params );
        signatureProcessDetailMapper.insertSignatureProcessDetail(signatureProcessDetail);


        /**2.2、插入报文信息*/
        Map<String, String> paramMap = new HashMap<String, String>();
        paramMap.putAll(params);

        paramMap.put("requestMsg",params.toString());
        paramMap.put("returnMsg",params.get("returnMsg"));
        paramMap.put("unnotifyMsg","");
        SignaturePlatformPkgMsg signaturePlatformPkgMsg = PackageParams.getPlatFormPkgmsg( paramMap );
        signaturePlatformPkgmsgMapper.insertSignaturePlatformPkgmsg( signaturePlatformPkgMsg );
        return contract;


    }

    @Override
    public SignatureContract updateProData(SignatureContract signatureContract, Map<String, String> params, Integer processFlag) throws Exception {
        return null;
    }


    @Transactional
    @Override
    public boolean signatureErrorUpdateData(SignatureContract signatureContract,Map<String, String> params) throws Exception {


        /**1.1、更新合同主表数据*/
        signatureContract.setStatus( Integer.parseInt( ContractStatus.合同签章处理失败.getType() ) );
        signatureContractInfoMapper.updateSignatureContract( signatureContract );


        /**2.1、更新状态主表数据*/

        Map<String, String> queryParams = new HashMap<String,String>();
        queryParams.put("signatureCode",signatureContract.getSignatureCode() );
        queryParams.put("contractCode",signatureContract.getContractCode() );
        queryParams.put("userId",   String.valueOf( signatureContract.getUserId() ) );
        SignatureProcessLog  signatureProcessLog = signatureProcessLogMapper.getSignatureProcessLogByCode(queryParams);
        signatureProcessLog.setBusinessStatus(BusinessStatus.处理中.getStatus());
        signatureProcessLog.setPlatformStatus(PlatFormStatus.同步处理失败.getStatus());
        signatureProcessLog.setPassStatus( PassStatus.待受理.getStatus());
        signatureProcessLogMapper.updateSignatureProcessLog( signatureProcessLog );

        /**2.2、新增过程明细表*/
        SignatureProcessDetail signatureProcessDetail = PackageParams.getSignatureProcessDetailPkgMsg( signatureProcessLog );
        signatureProcessDetailMapper.insertSignatureProcessDetail(signatureProcessDetail);

        /**2.2、增加通道报文信息*/
        SignaturePlatformPkgMsg signaturePlatformPkgMsg =  PackageParams.getPlatFormPkgmsg( params );
        signaturePlatformPkgmsgMapper.insertSignaturePlatformPkgmsg( signaturePlatformPkgMsg );
        return false;

    }


    /**
     * 更新中间状态数据，用于合同生成的四个阶段
     * 1、合同渲染
     * 2、上传文档
     * 3、合同签章
     * 4、合同归档
     * @param signatureContract
     * @param params
     * @return
     * @throws Exception
     */
    @Transactional
    @Override
    public boolean signatureUpdateProcessData(SignatureContract signatureContract,Map<String, String> params,String processFlag ) throws Exception {


        /**1.1、更新合同主表数据*/
        signatureContract.setStatus( Integer.parseInt( ContractStatus.合同签章处理中.getType()) );
        signatureContractInfoMapper.updateSignatureContract( signatureContract );

        /**2.1、更新状态主表数据*/

        Map<String, String> queryParams = new HashMap<String,String>();
        queryParams.put("signatureCode",signatureContract.getSignatureCode() );
        queryParams.put("contractCode",signatureContract.getContractCode() );
        queryParams.put("userId",   String.valueOf( signatureContract.getUserId() ) );
        SignatureProcessLog  signatureProcessLog = signatureProcessLogMapper.getSignatureProcessLogByCode(queryParams);
        signatureProcessLog.setInterfaceType( Integer.parseInt(processFlag));
        signatureProcessLog.setBusinessStatus(BusinessStatus.处理中.getStatus());
        signatureProcessLog.setPlatformStatus(PlatFormStatus.处理中.getStatus());
        signatureProcessLog.setPassStatus( PassStatus.待受理.getStatus());
        signatureProcessLog.setProcessFlag(ProcessFlag.处理中.getType() );
        signatureProcessLogMapper.updateSignatureProcessLog( signatureProcessLog );

        /**2.2、新增过程明细表*/
        SignatureProcessDetail signatureProcessDetail = PackageParams.getSignatureProcessDetailPkgMsg( signatureProcessLog );
        signatureProcessDetail.setInterfaceType( Integer.parseInt( processFlag ));
        signatureProcessDetailMapper.insertSignatureProcessDetail(signatureProcessDetail);

        /**3.2、新增报文表*/
        Map<String, String> paramMap = new HashMap<String, String>();
        paramMap.putAll(params);
        paramMap.put("requestMsg",params.toString());
        paramMap.put("returnMsg","");
        paramMap.put("unnotifyMsg","");
        SignaturePlatformPkgMsg signaturePlatformPkgMsg = PackageParams.getInsertSendPkgMsgInfo( paramMap );
        signaturePlatformPkgMsg.setInterfaceType( Integer.parseInt( processFlag ));
        signaturePlatformPkgmsgMapper.insertSignaturePlatformPkgmsg( signaturePlatformPkgMsg );

        return false;

    }


    @Transactional
    @Override
    public boolean notifySignatureUpdateProcessData(SignatureContract signatureContract,String processFlag ) throws Exception {
        /**1.1、更新合同主表数据*/
        signatureContract.setStatus( Integer.parseInt( ContractStatus.合同签章完成.getType()) );
        signatureContractInfoMapper.updateSignatureContract( signatureContract );

        /**2.1、更新状态主表数据*/

        Map<String, String> queryParams = new HashMap<String,String>();
        queryParams.put("signatureCode",signatureContract.getSignatureCode() );
        queryParams.put("contractCode",signatureContract.getContractCode() );
        queryParams.put("userId",   String.valueOf( signatureContract.getUserId() ) );
        SignatureProcessLog  signatureProcessLog = signatureProcessLogMapper.getSignatureProcessLogByCode(queryParams);
        signatureProcessLog.setInterfaceType( Integer.parseInt(processFlag));
        signatureProcessLog.setBusinessStatus(BusinessStatus.异步回执成功.getStatus());
        signatureProcessLog.setPlatformStatus(PlatFormStatus.异步处理成功.getStatus());
        signatureProcessLog.setPassStatus( PassStatus.异步处理成功.getStatus());
        signatureProcessLog.setProcessFlag(ProcessFlag.处理完成.getType() );
        signatureProcessLogMapper.updateSignatureProcessLog( signatureProcessLog );

        /**2.2、新增过程明细表*/
        SignatureProcessDetail signatureProcessDetail = PackageParams.getSignatureProcessDetailPkgMsg( signatureProcessLog );
        signatureProcessDetail.setInterfaceType( Integer.parseInt( processFlag ));
        signatureProcessDetailMapper.insertSignatureProcessDetail(signatureProcessDetail);

       return true;
    }

    @Transactional
    @Override
    public boolean updateCompleteSignatureProcessData(SignatureContract signatureContract, Map<String, String> params, String processFlag,Map<String, String> rtnUploadMap)  {
        try
        {
            /**2.1、更新状态主表数据*/
            Map<String, String> queryParams = new HashMap<String,String>();
            queryParams.put("signatureCode",signatureContract.getSignatureCode() );
            queryParams.put("contractCode",signatureContract.getContractCode() );
            queryParams.put("userId",   String.valueOf( signatureContract.getUserId() ) );
            SignatureProcessLog  signatureProcessLog = signatureProcessLogMapper.getSignatureProcessLogByCode(queryParams);
            signatureProcessLog.setInterfaceType( Integer.parseInt(processFlag));
            signatureProcessLog.setBusinessStatus(BusinessStatus.处理中.getStatus());
            signatureProcessLog.setPlatformStatus(PlatFormStatus.同步处理成功.getStatus());
            signatureProcessLog.setPassStatus( PassStatus.同步处理成功.getStatus());
            signatureProcessLog.setProcessFlag(ProcessFlag.处理完成.getType() );
            signatureProcessLogMapper.updateSignatureProcessLog( signatureProcessLog );

            /**2.2、新增过程明细表*/
            SignatureProcessDetail signatureProcessDetail = PackageParams.getSignatureProcessDetailPkgMsg( signatureProcessLog );
            signatureProcessDetail.setInterfaceType( Integer.parseInt( processFlag ));
            signatureProcessDetailMapper.insertSignatureProcessDetail(signatureProcessDetail);

            /**3.2、更新报文表*/
            Map<String, String> paramMap = new HashMap<String, String>();
            paramMap.putAll(params);
            paramMap.put("requestMsg",params.toString());

            paramMap.put("unnotifyMsg","");
            SignaturePlatformPkgMsg signaturePlatformPkgMsg = PackageParams.getCompleteSendPkgMsgInfo( paramMap );
            signaturePlatformPkgMsg.setInterfaceType( Integer.parseInt( processFlag ));
            signaturePlatformPkgMsg.setReturnMsg( rtnUploadMap.toString() );
            signaturePlatformPkgmsgMapper.updateSignaturePlatformPkgMsg( signaturePlatformPkgMsg );
            return true;
        }catch ( Exception e ){
             e.printStackTrace();
             //无需处理，由业务层处理
        }
        return false;
    }

    @Override
    public boolean receiveSignatureSaveData(SignatureContract signatureContractInfo, Map<String, String> params) throws Exception {
        return false;
    }

    @Override
    public Integer updateUrlsByConNo(Map<String, String> paramMap) {
        return signatureContractInfoMapper.updateUrlsByConNo(paramMap);
    }

    @Transactional
    @Override
    public boolean insertRvcPkgMsgInfo(Map<String, String> params) throws Exception {

        /**插入报文信息*/
        Map<String, String> paramMap = new HashMap<String, String>();
        paramMap.putAll(params);
        paramMap.put("requestMsg",params.toString());
        paramMap.put("returnMsg","");
        paramMap.put("unnotifyMsg","");
        SignatureBusinessPkgmsg signatureBusinessPkgmsg = PackageParams.getInsertRvcPkgMsgInfo( paramMap );
        signatureBusinessPkgmsgMapper.insertSignatureBusinessPkgmsg( signatureBusinessPkgmsg );
        return true;
    }

    @Transactional
    @Override
    public boolean updateRvcPkgMsgInfo(Map<String, String> params) throws Exception {

        /** 报文信息*/
        SignatureBusinessPkgmsg signatureBusinessPkgmsg = PackageParams.getUpdateRvcPkgMsgInfo( params );
        signatureBusinessPkgmsgMapper.updateSignatureBusinessPkgmsg( signatureBusinessPkgmsg );

        //更新合同url
       /* Map<String, String> updateContInfo = new HashMap<String, String>();
        updateContInfo.put("contractDownloadUrl", params.get("downloadUrl"));
        updateContInfo.put("contractViewUrl", params.get("viewpdfUrl"));
        updateContInfo.put("contractNo", params.get("contractCode"));
        updateContInfo.put("userId", params.get("userId"));
        signatureContractInfoMapper.updateUrlsByConNo(updateContInfo);*/

        return true;

    }

    @Transactional
    @Override
    public boolean insertSendPkgMsgInfo(Map<String, String> params) throws Exception {
        /**插入报文信息*/

        Map<String, String> paramMap = new HashMap<String, String>();
        paramMap.putAll(params);

        paramMap.put("returnMsg","");
        paramMap.put("unnotifyMsg","");
        SignaturePlatformPkgMsg  signaturePlatformPkgMsg = PackageParams.getInsertSendPkgMsgInfo( paramMap );
        signaturePlatformPkgmsgMapper.insertSignaturePlatformPkgmsg( signaturePlatformPkgMsg );
        return true;
    }

    @Transactional
    @Override
    public boolean updateSendPkgMsgInfo(Map<String, String> params) throws Exception {
        /**插入报文信息*/
        Map<String, String> paramMap = new HashMap<String, String>();
        paramMap.putAll(params);
        paramMap.put("returnMsg", params.toString() );
        paramMap.put("unnotifyMsg","");
        SignaturePlatformPkgMsg  signaturePlatformPkgMsg = PackageParams.getUpdateSendPkgMsgInfo( paramMap );
        signaturePlatformPkgmsgMapper.updateSignaturePlatformPkgMsg( signaturePlatformPkgMsg );
        return true;
    }

    @Override
    public Integer updateBySignatureCode(Map<String, String> paramMap) {
        return signatureContractDetailMapper.updateBySignatureCode(paramMap);
    }
}